package net.toocruel.iqismart.web.init;

import net.toocruel.iqismart.entity.setting.Setting;
import net.toocruel.iqismart.service.SettingService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 默认的sql文件初始化器，永远在其他数据初始化器之前执行
 * 默认执行sql文件classpath下的init.sql
 * 可增加自己的sql文件，application.properties中添加配置：
 * web.init.sqlFiles=init.sql,my.sql
 * 多个文件用逗号分隔
 * 必须放在classpath下即src/main/resources目录
 *
 * @author toocruel
 *
 */
@Component
public class SQLDataInitializer extends AbstractDataInitializer implements DataInitializer {

    @Value("${web.init.sqlFiles:init.sql}")
    private String initSqlFileName ;

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    private EntityManager entityManager ;

    @Autowired
    private SettingService settingService;

    @Override
    protected void doInit() throws Exception {
        try {
            entityManager.joinTransaction();
            String[] sqlFileArray = initSqlFileName.split(",");
            Arrays.stream(sqlFileArray).forEach(sqlFile ->{
                String initSql = null;
                try {
                    File file = ResourceUtils.getFile("classpath:"+sqlFile);
                    initSql = FileUtils.readFileToString(file, Charset.forName("utf-8"));
                } catch (IOException e) {
                    return;
                }
                String[] initSqlArray = initSql.split("--##--");
                Arrays.stream(initSqlArray).forEach(sql -> {
                    sql = sql.replace("\n", "");
                    sql = sql.replace("\t", "");
                    entityManager.createNativeQuery(sql).executeUpdate();
                });
            });
            Setting setting = settingService.getSetting();
            setting.setInited(true);
            settingService.update(setting);


        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(SQLDataInitializer.class.getSimpleName()+"执行失败");
        }

    }

    @Override
    protected boolean isNeedInit() {
        if(entityManager == null){
            entityManager = entityManagerFactory.createEntityManager();
        }

        return settingService.getSetting()==null || !settingService.getSetting().isInited();
    }

    @Override
    public Integer getIndex() {
        return 2;
    }
}
